package com.example.votes.controller;

import com.example.votes.entity.Image;
import com.example.votes.service.ImageService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/votes")
public class VotesController {

    private final ImageService imageService;

    public VotesController(ImageService imageService) {
        this.imageService = imageService;
    }

    @GetMapping
    public Map<String, Object> getVotes() {
        List<Image> images = imageService.listSortedByVotesDesc();
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("CharactersNum", images.size());
        for (int i = 0; i < images.size(); i++) {
            result.put("Name_" + (i + 1), images.get(i).getImageName());
            result.put("Count_" + (i + 1), images.get(i).getVoteCount());
        }
        return result;
    }
}